import React from 'react';
import {
  Table,
  Form,
  Input,
  Select,
  Button,
  Upload,
  Popconfirm,
  Tooltip,
  Switch,
  message,
} from 'antd';
import { connect } from 'dva';
import ModalC from 'components/Modal/domain/domain';
import moment from 'moment';

const Search = Input.Search;
const Option = Select.Option;

@connect(state => ({
  domain: state.domain,
  global: state.global,
  dns: state.dns,
}))
class Pages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      domainGroupId: null,
      visible: false,
      formatData: null,
      selectedRowKeys: [],
      type: 'add',
      currentId: null,
      searchValue: '',
      switchLoading: false,
    };
  }

  /**
   * 获取所有域名组组列表
   */
  getAllEquipment = () => {
    this.props.dispatch({
      type: 'domain/getAllList',
      payload: {},
      callback: data => {
        this.setState(
          {
            domainGroupId: data.id,
          },
          () => this.getList()
        );
      },
    });
  };

  /**
   * 筛选
   */
  select = value => {
    this.setState(
      {
        domainGroupId: value,
      },
      () => this.getList()
    );
  };

  //获取列表数据
  getList = (pageNum = 1, pageSize = 10) => {
    const { domainGroupId, searchValue } = this.state;
    this.props.dispatch({
      type: 'domain/getList',
      payload: {
        domainGroupId,
        pageNum,
        pageSize,
        domain: searchValue,
      },
    });
  };

  //提交数据
  submit = values => {
    const { type, currentId } = this.state;
    if (type === 'add') {
      this.props.dispatch({
        type: 'domain/add',
        payload: {
          ...values,
        },
        callback: () => {
          this.setState(
            {
              groupId: values.groupId,
            },
            () => this.getList()
          );
          this.closeModal();
        },
      });
    } else {
      this.props.dispatch({
        type: 'domain/edit',
        payload: {
          ...values,
          id: currentId,
        },
        callback: () => {
          this.getList();
          this.closeModal();
        },
      });
    }
  };

  /**
   * 删除
   */
  delete = ids => {
    this.props.dispatch({
      type: 'domain/delete',
      payload: {
        ids,
      },
      callback: () => {
        this.setState({
          selectedRowKeys: [],
        });
        this.getList();
      },
    });
  };
  deleteAll = () => {
    const { selectedRowKeys } = this.state;
    this.delete(selectedRowKeys);
  };
  //批量删除
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  /**
   * modal
   */
  closeModal = () => {
    this.setState({
      visible: false,
      formatData: null,
    });
  };
  //新增编辑
  updateBtn = (type = 'add', record = null) => {
    if (type === 'add') {
      this.setState({
        type: 'add',
        visible: true,
      });
    } else {
      this.setState({
        type: 'edit',
        currentId: record.id,
        visible: true,
        formatData: record,
      });
    }
  };

  /**
   * 刷新
   */
  freshDns = () => {
    this.props.dispatch({
      type: 'dns/freshDns',
      payload: {},
    });
  };

  //搜索
  search = value => {
    this.setState(
      {
        searchValue: value,
      },
      () => this.getList()
    );
  };
  /**
   * 切换switch
   */
  handleSwitch = value => {
    this.setState({
      switchLoading: true,
      currentId: value.id,
    });
    this.props.dispatch({
      type: 'domain/edit',
      payload: {
        openState: value.openState === 1 ? 0 : 1,
        id: value.id,
      },
      callback: () => {
        this.getList();
        this.setState({
          currentId: null,
          switchLoading: false,
        });
      },
    });
  };

  /**
   * 翻页
   */
  pageChange = page => {
    this.getList(page);
  };

  /**
   * 导入
   */
  upload = data => {
    if (data.file.status === 'done') {
      if (data.file.response.code === 200) {
        message.info('导入成功');
        this.getList();
      } else {
        message.error(data.file.response.msg);
      }
    }
  };

  componentDidMount() {
    this.getAllEquipment();
  }

  render() {
    const {
      domain: { list, loading, allList, total, pageSize, pageNum },
    } = this.props;
    const {
      domainGroupId,
      visible,
      formatData,
      selectedRowKeys,
      type,
      switchLoading,
      currentId,
    } = this.state;

  

    const pagination = {
      total,
      pageSize,
      current: pageNum,
      onChange: this.pageChange,
    };

    const colomns = [
      {
        title: '所属域名组',
        width: 80,
        dataIndex: 'domainGroupId',
        render: (text, record) => {
          let arr =allList.length>0 && allList.filter(item => item.id === text);
          if(arr.length>0) {
            return <span>
              {arr[0].groupTitle}
            </span>
          }
        }
      },
      {
        title: '域名',
        dataIndex: 'domain',
        width: 80,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        width: 100,
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        width: 100,
        render: text => <span>{moment(text).format('YYYY年MM月DD日')}</span>,
      },
      {
        title: '更新时间',
        dataIndex: 'updateDate',
        width: 100,
        render: text => <span>{moment(text).format('YYYY年MM月DD日')}</span>,
      },
      {
        title: '状态',
        dataIndex: 'openState',
        width: 100,
        render: (text, record) => (
          <Switch
            loading={switchLoading && currentId === record.id}
            onChange={() => this.handleSwitch(record)}
            checked={text === 1}
            checkedChildren="开"
            unCheckedChildren="关"
          />
        ),
      },
      {
        title: '操作',
        width: 80,
        render: (text, record) => (
          <>
            <span onClick={() => this.updateBtn('edit', record)} className="btnG">
              编辑
            </span>
          </>
        ),
      },
    ];

    const rowSelection = {
      columnWidth: 10,
      onChange: this.onSelectChange,
    };

    return (
      <>
        <h3 className="head">域名管理</h3>
        <div style={{ padding: '10px 20px' }}>
          <div>
            <span>域名组:</span>
            <Select
              value={domainGroupId}
              onChange={this.select}
              style={{ width: '200px', marginLeft: '10px' }}
            >
              {allList.map(item => (
                <Option value={item.id} key={item.id}>
                  <Tooltip placement="topLeft" title={item.groupTitle}>
                    <span>{item.groupTitle}</span>
                  </Tooltip>
                </Option>
              ))}
            </Select>
            <Search
              enterButton
              placeholder="输入域名搜索"
              style={{ width: '250px', marginLeft: '20px' }}
              onSearch={this.search}
            />
          </div>

          {selectedRowKeys.length > 0 && (
            <Popconfirm
              title="确定要删除吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => this.deleteAll()}
            >
              <Button style={{ marginTop: '20px' }} type="primary" icon="delete">
                批量删除
              </Button>
            </Popconfirm>
          )}

          <Popconfirm
            title="确定要启用配置吗"
            okText="确定"
            cancelText="取消"
            onConfirm={() => this.freshDns()}
          >
            <Button className="ml10 mt20" type="primary" icon="tool">
              启用配置
            </Button>
          </Popconfirm>
          <Upload
            action="/api/api/v1/domain/importExcel"
            headers={{
              accessToken: localStorage.getItem('tokenId'),
            }}
            onChange={this.upload}
            showUploadList={false}
          >
            <Button className="ml10" type="primary" icon="import">
              导入
            </Button>
          </Upload>

          <Table
            rowKey="id"
            loading={loading}
            columns={colomns}
            dataSource={list}
            rowSelection={rowSelection}
            pagination={pagination}
          />
          <Button type="primary" onClick={() => this.updateBtn()}>
            新增域名
          </Button>

          <ModalC
            type={type}
            list={allList}
            visible={visible}
            close={this.closeModal}
            formatData={formatData}
            submit={this.submit}
          />
        </div>
      </>
    );
  }
}

export default Pages;
